package cn.shengchao.examstar.knowledge.application;

import cn.shengchao.examstar.knowledge.application.dto.KnowledgePointDetailDTO;
import cn.shengchao.examstar.knowledge.application.query.GetKnowledgePointDetailQuery;
import cn.shengchao.examstar.knowledge.domain.entity.KnowledgePoint;
import cn.shengchao.examstar.knowledge.domain.entity.KnowledgePointMastery;
import cn.shengchao.examstar.knowledge.domain.repository.KnowledgePointMasteryRepository;
import cn.shengchao.examstar.knowledge.domain.repository.KnowledgePointRepository;
import cn.shengchao.examstar.product.acl.adapters.repositories.SpecificationTypeRepository;
import cn.shengchao.examstar.product.infrastructure.dao.po.TSpecificationType;
import cn.shengchao.examstar.shared.application.ai.AiKnowledgeSharedService;
import cn.shengchao.examstar.shared.domain.ai.dto.KnowledgePointDescriptionSharedDTO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class KnowledgeApplicationService {

    private final KnowledgePointRepository knowledgePointRepository;
    private final KnowledgePointMasteryRepository knowledgePointMasteryRepository;
    private final AiKnowledgeSharedService aiKnowledgeSharedService;
    private final SpecificationTypeRepository specificationTypeRepository;

    public KnowledgePointDetailDTO getKnowledgePointDetail(@Valid GetKnowledgePointDetailQuery query) {
        log.info("查询知识点详情: {}", query);

        KnowledgePoint knowledgePoint = knowledgePointRepository.findById(query.getKnowledgePointId())
                .orElseThrow(() -> new RuntimeException("知识点不存在!"));

        boolean needsGeneration = !StringUtils.hasText(knowledgePoint.getCoreConcept())
                || !StringUtils.hasText(knowledgePoint.getKeyPoints())
                || !StringUtils.hasText(knowledgePoint.getLearningSuggestions());

        if (needsGeneration) {
            log.info("知识点 {} 的详情不完整，调用大模型生成并保存.", query.getKnowledgePointId());
            Long specificationTypeId = knowledgePoint.getSpecificationTypeId();
            List<TSpecificationType> specificationTypes = specificationTypeRepository.getSpecificationTypesByIdList(List.of(specificationTypeId));
            // 调用AI服务生成知识点详情
            KnowledgePointDescriptionSharedDTO description = aiKnowledgeSharedService.generateKnowledgeDescription(
                    query.getUserId(),
                    knowledgePoint.getName(),
                    specificationTypes.stream().map(TSpecificationType::getName).collect(Collectors.joining())
            );

            // 更新知识点详情
            knowledgePoint.setCoreConcept(description.getCoreConcept());
            knowledgePoint.setKeyPoints(description.getKeyPoints());
            knowledgePoint.setLearningSuggestions(description.getLearningSuggestions());
            knowledgePointRepository.save(knowledgePoint);

            log.info("知识点 {} 的详情已生成并保存", query.getKnowledgePointId());
        }

        Optional<KnowledgePointMastery> masteryOpt = knowledgePointMasteryRepository
                .findByUserIdAndKnowledgePointId(query.getUserId(), query.getKnowledgePointId());

        String degreeOfMastery = masteryOpt.map(KnowledgePointMastery::getDegreeOfMastery).orElse("N");
        String degreeOfMasteryDesc = masteryOpt.map(KnowledgePointMastery::getMasteryDescription).orElse("未检测");

        return KnowledgePointDetailDTO.builder()
                .knowledgePointId(knowledgePoint.getId())
                .knowledgePointName(knowledgePoint.getName())
                .degreeOfMastery(degreeOfMastery)
                .degreeOfMasteryDesc(degreeOfMasteryDesc)
                .coreConcepts(knowledgePoint.getCoreConcept())
                .status(masteryOpt.map(KnowledgePointMastery::getStatus).orElse(1))
                .keyPoints(knowledgePoint.getKeyPoints())
                .studySuggestions(knowledgePoint.getLearningSuggestions())
                .build();
    }
} 